package com.szf.base.web;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.szf.base.bean.SinlogConstants;

public class LoginFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String uri = req.getRequestURI();
		Pattern p = Pattern.compile("login(.*)action");
		Pattern cp = Pattern.compile("task!authCallback.action");
		boolean isLogin = p.matcher(uri).find() || cp.matcher(uri).find();
		if (!isLogin) {
			HttpSession session = req.getSession(false);
			if (session == null || session.getAttribute(SinlogConstants.PRINCIPLE_KEY) == null) {
				HttpServletResponse ros = (HttpServletResponse) response;
				String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/";
				ros.sendRedirect(basePath);
				return;
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
